package cn.rengy.web.framework.wxmp.qrcode;

import java.util.concurrent.ScheduledExecutorService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.wxmp.QrcodeTargetTable;

@Service
public class GetWxQrcodeService {
	private static Logger logger = LoggerFactory.getLogger(GetWxQrcodeService.class);
	@Autowired
	private WxQrcodeService wxQrcodeService;
	@Autowired
	private DbService dbService;
	
	@Autowired
	private ScheduledExecutorService scheduledExecutorService;
	/**
	 * 取出一个空闲的二维码
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW)//独立事务
	public WxQrcodeEntity get(String appid,QrcodeTargetTable target_table,String target_id) {
		//为了获取正确值，锁表，为了快读释放锁，使用独立事务
		WxQrcodeEntity e=this.dbService.queryForBean("lock_get_available_wxqrcode",WxQrcodeEntity.class,appid);
		if(e==null) { //新增二维码
			e=wxQrcodeService.add(appid);
		}
		//更新状态 1空闲2提取中3已占用4已回收
		this.dbService.update("update_wxqrcode_qr_status2",2,target_table.toString(),target_id,e.getScene_str());
		/*
		 * if(i==0) { throw new BusinessException("获取二维码异常:{}",e.getScene_str()); }
		 */
		return e;
	}
	
	/**
	 * 取消使用
	 * @param scene_str
	 */
	public void cancel(String scene_str) {
		this.dbService.update("update_wxqrcode_qr_status0",1,scene_str);
		/*
		 * if(i==0) { logger.error("取消使用二维码异常:{}",scene_str); }
		 */
	}
	/**
	 * 确认使用
	 * @param scene_str
	 */
	@Transactional(propagation = Propagation.MANDATORY)//强制事务
	public void confirm(String scene_str) {
		this.dbService.update("update_wxqrcode_qr_status0",3,scene_str);
		/*
		 * if(i==0) { throw new BusinessException("确认使用二维码异常:{}",scene_str); }
		 */
	}
	
}
